package com.innovation.chengzhangriji.ui.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.util.ChZhRJUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

public class PhotosAdapter extends RecyclerView.Adapter<PhotoViewHolder> implements PhotoViewHolder.OpenPictureListener {

    public interface OnClickAdapterListener {

        void onClickAdd();

        void onClickRemove();
    }

    private Context mContext;

    private ArrayList<Photo> mArrayList;

    private DisplayImageOptions options; //配置图片加载及显示选项

    private int mCount;

    private OnClickAdapterListener mOnClickAdapterListener;

    public PhotosAdapter(Context context) {
        mContext = context;
        mArrayList = new ArrayList<Photo>();
        setOptions();
    }

    @Override
    public PhotoViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_photo, viewGroup, false);
        PhotoViewHolder viewHolder = new PhotoViewHolder(mContext, view);
        viewHolder.setOpenPictureListener(this);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(PhotoViewHolder holder, int position) {
        ImageLoader.getInstance().displayImage("file://" + mArrayList.get(position).getUrl(), holder.getPicture(), options, null);
        holder.setSelect(mArrayList.get(position).isSelect());
    }

    // 判断图片的方向，进行图片旋转
    private String rotateImage(String filePath) {
        String rotatePath = filePath;
        try {
            ExifInterface exifInterface = new ExifInterface(filePath);
            int angle = 0;
            int rotate = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
            if(rotate == ExifInterface.ORIENTATION_ROTATE_90) {
                angle = 90;
            } else if (rotate == ExifInterface.ORIENTATION_ROTATE_180) {
                angle = 180;
            } else if (rotate == ExifInterface.ORIENTATION_ROTATE_270) {
                angle = 270;
            }
            System.out.println(rotate);
            if(angle != 0) {
                rotatePath = new File(Config.getDir(mContext, Config.PHOTO_DIR), new File(filePath).getName()).getPath();
                if(new File(rotatePath) == null || !new File(rotatePath).exists()) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Bitmap.Config.RGB_565;
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(filePath, options);
                    if (options.outWidth < 0 || options.outHeight < 0) {
                        return filePath;
                    }
                    options.inJustDecodeBounds = false;
                    generateSimpleSize(options);
                    Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
                    Matrix matrix = new Matrix();
                    matrix.postRotate(angle);
                    Bitmap rotateBitmap = Bitmap.createBitmap(
                            bitmap, 0, 0, options.outWidth, options.outHeight, matrix, true);
                    if(rotateBitmap != null) {
                        bitmap.recycle();
                        FileOutputStream out = new FileOutputStream(rotatePath);
                        rotateBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                        out.close();
                        rotateBitmap.recycle();
                    }
                }
                System.out.println(rotatePath);
            }
        } catch (OutOfMemoryError outOfMemoryError) {
            Log.e("TAG", "can't load image, OutOfMemoryError!!!");
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return rotatePath;
        }
    }

    /**
     * 生成 inSimpleSize
     * @param options
     */
    private void generateSimpleSize(BitmapFactory.Options options) {
        final int size = (int) ChZhRJUtils.dp2px(480, mContext.getResources().getDisplayMetrics());
        int scaleWidth = options.outWidth / size;
        int scaleHeight = options.outHeight / size;
        int scaleMin = Math.max(scaleWidth, scaleHeight);
        if(scaleMin < 1) {
            scaleMin = 1;
        }
        options.inSampleSize = scaleMin;
    }

    @Override
    public int getItemCount() {
        if (mArrayList != null) {
            return mArrayList.size();
        }
        return 0;
    }

    @Override
    public void openPicture(int position) {

    }

    @Override
    public void isSelect(int position) {
        if (!mArrayList.get(position).isSelect()) {
            if (mCount >= 9) {
                Toast.makeText(mContext, "最多选择9张照片", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (!mArrayList.get(position).isSelect()) {
            mCount++;
            mArrayList.get(position).setSelect(true);
            if (mOnClickAdapterListener != null) {
                mOnClickAdapterListener.onClickAdd();
            }
        } else {
            mCount--;
            mArrayList.get(position).setSelect(false);
            if (mOnClickAdapterListener != null) {
                mOnClickAdapterListener.onClickRemove();
            }
        }
        notifyItemChanged(position);
    }

    public void setOnClickAdapterListener(OnClickAdapterListener listener) {
        mOnClickAdapterListener = listener;
    }

    public String[] getUrls() {
        ArrayList<String> urlList = new ArrayList<String>();
        for (int i = 0; i < mArrayList.size(); i++) {
            if (mArrayList.get(i).isSelect()) {
                urlList.add(mArrayList.get(i).getUrl());
            }
        }
        return urlList.toArray(new String[urlList.size()]);
    }

    public void addImageUrl(String imageUrl) {
        Photo photo = new Photo();
        photo.setUrl(rotateImage(imageUrl));
//        photo.setUrl(imageUrl);
        mArrayList.add(photo);
    }

    // 配置图片加载及显示选项
    private void setOptions() {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_photo_empty)    //在ImageView加载过程中显示图片
                .showImageForEmptyUri(R.drawable.ic_photo_empty)  //image连接地址为空时
                .showImageOnFail(R.drawable.ic_photo_empty)  //image加载失败
                        // .cacheInMemory(true)  //加载图片时会在内存中加载缓存
                        // .cacheOnDisk(true)   //加载图片时会在磁盘中加载缓存
                .build();
    }

    private class Photo {

        private boolean isSelect;

        private String url;

        public boolean isSelect() {
            return isSelect;
        }

        public void setSelect(boolean isSelect) {
            this.isSelect = isSelect;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}
